#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2019/11/23 14:59
# @Author  : Wang Feng
# @FileName: excel_utils.py
# @Software: PyCharm
import xlrd
import os


class E2TCUtils:

    """
    按指定格式解析用例文件
    param：path excel文件路径
    return：test_cases 用例集合 list
    """
    @classmethod
    def __parse(cls, f):
        excel = xlrd.open_workbook(file_contents=f)
        sheet = excel.sheet_by_index(0)
        nrows = sheet.nrows
        ncols = sheet.ncols
        print("获取到行数：%s" % nrows)
        print("获取到列数：%s" % ncols)

        # 初始化用例key
        test_case_key = list()
        # 获取用例字段表头
        for col in range(ncols):
            key = sheet.cell(6, col).value
            test_case_key.append(key)

        # 初始化用例集合
        test_cases = list()

        # 获取用例
        for row in range(7, nrows):
            # 初始化用例value
            test_case_value = list()
            for col in range(ncols):
                value = sheet.cell(row, col).value
                test_case_value.append(value)
            # 合并用例key-value,并转换为字典类型
            meta_test_case = dict(zip(test_case_key, test_case_value))
            test_cases.append(meta_test_case)
        return test_cases

    @classmethod
    def to_test_cases(cls, path):
        """
        转换为用例对象集合
        param: path 文件路径
        return test_cases 用例对象集合 list
        """
        cases = cls.__parse(path)
        test_cases = list()
        epic = str()
        feature = str()
        story = str()
        for case in cases:
            # test_case = TestCase(case)
            if case['epic']:
                epic = case['epic']
            if case['feature']:
                feature = case['feature']
            if case['story']:
                story = case['story']

            case['epic'] = epic
            case['feature'] = feature
            case['story'] = story

            test_cases.append(case)
        test_cases = list(filter(lambda test_case: test_case['title'] != '', test_cases))
        print('共计用例数: %s' %len(test_cases))
        return test_cases


if __name__ == '__main__':
    print(os.path.join(os.path.dirname(__file__), '军民融合app自动化测试用例二期.xlsx'))
    test_cases = E2TCUtils.to_test_cases(os.path.join(os.path.dirname(__file__), '军民融合app自动化测试用例二期.xlsx'))
    print('生成用例数: ' + str(len(test_cases)))
    for i in test_cases:
        print(i)